from sentinelsat import SentinelAPI
import datetime
import os
import threading
from flask import request, jsonify, Blueprint
import logging
import time
import requests
import shutil


sentinel2_api = Blueprint('sentinel2_api', __name__)


@sentinel2_api.route(rule='/sentinel2/download/', methods=['GET','post'])
def download():
    "下载"
    # POST方式获取参数
    jsondata = request.get_json()
    save_dir = jsondata['save_dir']
    productids = jsondata["productids"]
    log_name = f"{jsondata['task_id']}.log"
    log_path = os.path.join(save_dir, log_name)
    username,password=jsondata["username"],jsondata["password"]
    apiurl='https://scihub.copernicus.eu/dhus/'
    api=SentinelAPI(username,password,apiurl,show_progressbars=False)
    thread=threading.Thread(
        target=api.download_all,args=(productids,save_dir))
    thread.setDaemon
    thread.start()
    
    titles=[api.get_product_odata(p)['title'] for p in productids] 
    
    threadlog=threading.Thread(
        target=getLogfile,args=(log_path,titles,save_dir,thread))
    threadlog.setDaemon
    threadlog.start()
    
    sendmsg={'msg':'开启下载', 'log_file': log_path, 'code':200}
    return jsonify(sendmsg)


def getLogfile(log_path,titles,save_dir,thread):
    logger = logging.getLogger("Sentinel-Download")
    logger.setLevel(level = logging.INFO)
    handler = logging.FileHandler(log_path)
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
    handler.setFormatter(formatter)
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    logger.addHandler(handler)
    logger.addHandler(console)
    sum = len(titles)
    while thread.is_alive():
        for title in titles:
            zip_path = os.path.join(save_dir, f'{title}.zip')
            if os.path.exists(zip_path):
                logger.info(f"Completed:{title}")
                titles.remove(title)
                logger.info(f"完成进度：{sum-len(titles)}/{sum}")
        if len(titles) == 0: logger.info(f"End!");break
        time.sleep(10)
    return


@sentinel2_api.route(rule='/sentinel2/search/', methods=['GET','post'])
def search():
    "搜索"
    jsondata = request.get_json()
    tiles=jsondata["tiles"]
    # folder=jsondata["save_dir"]
    start_date,end_date = jsondata["startdate"],jsondata["enddate"]
    clouds = jsondata["clouds"]
    username,password=jsondata["username"],jsondata["password"]
    start_date=datetime.datetime.strptime(start_date,"%Y-%m-%d")
    end_date,dateformat = f"{end_date} 23:59:59","%Y-%m-%d %H:%M:%S"
    end_date = datetime.datetime.strptime(end_date, dateformat)
    apiurl='https://scihub.copernicus.eu/dhus/'
    api=SentinelAPI(username,password,apiurl,show_progressbars=False)
    kwargs={
        'platformname':'Sentinel-2',
        'producttype':'S2MSI1C',
        'date':(start_date, end_date),
        'cloudcoverpercentage':(0, clouds)}
    productinfos = {}
    for t in tiles:productinfos.update(api.query(tileid=t,**kwargs))
    sendmsg={'msg':'检索结果','product_infos':productinfos,'code':200}
    # thread = threading.Thread(
    #     target=api.download_all_quicklooks,args=(productinfos.keys(),folder,4))
    # thread.setDaemon
    # thread.start()
    return jsonify(sendmsg)



@sentinel2_api.route(rule='/sentinel2/thumbnail/',methods=['GET','post'])
def thumbnail():
    jsondata = request.get_json()
    username, password = jsondata['username'], jsondata['password']
    apiurl='https://scihub.copernicus.eu/dhus/'
    session = requests.Session()
    session.auth = (username, password)
    user_agent = "sentinelsat/" + "1.1.1"
    session.headers["User-Agent"] = user_agent
    session.timeout  = 60
    folder = jsondata['save_dir']
    productid = jsondata['productid']
    url = f"{apiurl}odata/v1/Products('{productid}')/Products('Thumbnail')/$value"
    responses = session.get(url, stream=True)
    filename = responses.headers['content-disposition'].split("=")[1].replace("\"","")
  
    jpg_path = os.path.join(folder, filename)
    if os.path.exists(jpg_path):
        return jsonify({'msg':'缩略图存在', 'jpg_path':jpg_path,'code':200})
    if responses.status_code == 200:
        with open(jpg_path,'wb') as files:
            responses.raw.decode_content = True
            shutil.copyfileobj(responses.raw, files)
        return jsonify({'msg':'获得缩略图成功','jpg_path':jpg_path,'code':200})
    else:
        return jsonify({'msg':'获得缩略图失败','jpg_path': 'error','code':500})
    

@sentinel2_api.route(rule='/sentinel2/quicklook/', methods=['GET','post'])
def quicklook():
    jsondata = request.get_json()
    username, password = jsondata['username'], jsondata['password']
    apiurl='https://scihub.copernicus.eu/dhus/'
    session = requests.Session()
    session.auth = (username, password)
    user_agent = "sentinelsat/" + "1.1.1"
    session.headers["User-Agent"] = user_agent
    session.timeout  = 60
    folder = jsondata['save_dir']
    productid = jsondata['productid']
    url = f"{apiurl}odata/v1/Products('{productid}')/Products('Quicklook')/$value"
    responses = session.get(url, stream=True)
    filename = responses.headers['content-disposition'].split("=")[1].replace("\"","")
    jpg_path = os.path.join(folder, filename)
    if os.path.exists(jpg_path):
        return jsonify({'msg':'快看图存在', 'jpg_path':jpg_path,'code':200})
    if responses.status_code == 200:
        with open(jpg_path,'wb') as files:
            responses.raw.decode_content = True
            shutil.copyfileobj(responses.raw, files)
        return jsonify({'msg':'获得快看图成功','jpg_path':jpg_path,'code':200})
    else:
        return jsonify({'msg':'获得快看图失败','jpg_path': 'error','code':500})
  